package com.xinyi;

/**
 * @desc:
 * @author: Shoko
 * @date: 2025/3/13
 */
import java.sql.*;

public class DatabaseProvider implements IDatabaseProvider{
    private Connection conn;

    // 数据库连接方法
    public void connection(String connectionString) {
        String url = connectionString;
        String user = "root";  // MySQL 用户名
        String password = "123456";  // MySQL 用户密码（这里设置为123456）

        try {
            // 使用连接字符串、用户名和密码建立连接
            conn = DriverManager.getConnection(url, user, password);
            if (conn != null) {
                System.out.println("数据库连接成功！");
            } else {
                System.out.println("数据库连接失败，连接对象为 null");
            }
        } catch (SQLException e) {
            System.out.println("数据库连接异常： " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 执行 SQL 查询
    public ResultSet executeSql(String query) {
        try {
            if (conn != null) {
                Statement stmt = conn.createStatement();
                return stmt.executeQuery(query);
            } else {
                System.out.println("数据库连接尚未建立！");
                return null;
            }
        } catch (SQLException e) {
            System.out.println("SQL 执行异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        DatabaseProvider databaseProvider = new DatabaseProvider();
        databaseProvider.connection("jdbc:mysql://localhost:3306/e3_q2?useSSL=false&serverTimezone=UTC");

        // 测试 SQL 查询
        ResultSet rs = databaseProvider.executeSql("SELECT * FROM users");
        try {
            while (rs != null && rs.next()) {
                System.out.println("token: " + rs.getString("token")) ;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
